package com.zwj.batch.config.test;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author 张文接
 * @version 1.0
 * @createTime 2023-05-21 16:21:00
 */
//@Configuration
public class BatchConfig02 {
    //job构造工厂
    @Resource
    private JobBuilderFactory jobBuilderFactory;
    //step构造工厂
    @Resource
    private StepBuilderFactory stepBuilderFactory;

    /**
     * 逻辑主体
     *
     * @return
     */
    @StepScope
    @Bean
    public Tasklet tasklet(@Value("#{jobParameters['name']}") String name) {
        return new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                /*
                方法一：获取批处理的入参
                Map<String, Object> jobParameters = chunkContext.getStepContext().getJobParameters();
                System.out.println("参数：name = " + jobParameters.get("name"));
                */

                //通过 注解    @StepScope、@Value延时加载获取参数，

                System.out.println("Hello job05-param,参数：" + name);
                return RepeatStatus.FINISHED;
            }
        };
    }

    @Bean
    public Job job() {
        return jobBuilderFactory.get("job05-param")//给job命名
                .start(step1())//具体执行什么步骤(step)
                .build();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory.get("step1")//给step命名
                .tasklet(tasklet(null))//注入具体要执行的逻辑
                .build();//构建
    }
}
